from core.settings import WEB_ROOT,UPLOAD_PATH
from django.http import HttpResponse
from django.utils import simplejson as json
import traceback,os
from uploadrules import uploadRules

def upload(request):
    try:
        modelType  = request.POST.get('modelType')
        param = request.POST.get('param')
        sfile = request.FILES['uploader']
        destfile = handle_uploaded_file(modelType,sfile,param)
        return HttpResponse(json.dumps({'code':1,'result':destfile}), mimetype='text/html')
    except Exception:
        return HttpResponse(json.dumps({'code':0,'message':traceback.format_exc()}), mimetype='text/html')

def __ensureDir(dir_path):
        if os.path.isdir(dir_path) :
            return;
        head,tail = os.path.split(dir_path)
        if head :
            __ensureDir(head)
        if tail :
            os.mkdir(dir_path)

def handle_uploaded_file(modelType,sfile,param):
    rule = uploadRules.getRule(modelType)
    uppath = rule.getUploadPath(modelType,param)
    dir_path = WEB_ROOT + '/' + UPLOAD_PATH + uppath + '/'
    __ensureDir(dir_path)
    filename = rule.getRenamedName(modelType,param,sfile.name)
    destination = open(dir_path + filename, 'wb+')
    for chunk in sfile.chunks():
        destination.write(chunk)
    destination.close()
    return '/' + UPLOAD_PATH + uppath + '/' + filename